package graphics;

import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.util.ArrayList;
import java.util.Collections;

import model.Sprite;

/**
 * Essa classe serve para renderizar objetos.
 * Ela recebe a chamada de draw e guarda o que deve ser renderizado, ao chamar end draw, ela analisa tudo e renderiza.
 * @author Ygor
 *
 */
public class SpriteBatch {
	private ArrayList<Sprite> sprites;
	private Graphics2D g;
	private static float deviceAlpha = 1f;
	
	public SpriteBatch ()
	{
		this.sprites = new ArrayList<Sprite>();
	}
	
	
	public void BeginDraw()
	{
		sprites.clear();
	}
	
	public void Draw(Sprite s)
	{
		sprites.add(s);
	}
	
	public void EndDraw()
	{	
		float compositeAlpha;
		Sprite s;
		
		Collections.sort(sprites);
		for (int i = 0; i < sprites.size(); i++) {
			s = sprites.get(i);
			
			// mix it with the sprite alpha
			compositeAlpha = deviceAlpha * s.getAlpha();
			// render with the mixed alpha
			g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, compositeAlpha));
			s.render(g);
		}
		// sets the original alpha.
		g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, deviceAlpha));
	}

	public static float getDeviceAlpha() {
		return deviceAlpha;
	}
	public static void setDeviceAlpha(float deviceAlpha) {
		if (deviceAlpha > 1)
			SpriteBatch.deviceAlpha = 1f;
		else if (deviceAlpha <= 0)
			SpriteBatch.deviceAlpha = 0f;
		else
			SpriteBatch.deviceAlpha = deviceAlpha;
	}
	public Graphics2D getGraphics() {
		return g;
	}
	public void setGraphics(Graphics2D g)
	{
		this.g = g;
	}
}
